﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Data;

namespace FrontEnd
{
	public class NodeTypeToContextMenuConverter : IValueConverter
	{
		private static Dictionary<NodeType, INodeMenuBuilable> _menuBuilderCache;

		static NodeTypeToContextMenuConverter()
		{
			// find and load all menus using reflection
			_menuBuilderCache = new Dictionary<NodeType, INodeMenuBuilable>();
			foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
			{
				if (t.GetInterface("INodeMenuBuilable") != null)
				{
					INodeMenuBuilable i = Activator.CreateInstance(t) as INodeMenuBuilable;
					var applicableNodeTypes = i.GetApplicableNodeTypes();
					foreach (var ant in applicableNodeTypes)
					{
						_menuBuilderCache.Add(ant, i);
					}
				}
			}
		}

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			Node n = value as Node;

			ContextMenu cm = null;
			if(_menuBuilderCache.ContainsKey(n.Type))
				cm = _menuBuilderCache[n.Type].BuildMenu(n);

			return cm;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
